package dk.mirasola.systemtraining.bridgewidgets.shared.factory;

import dk.mirasola.systemtraining.bridgewidgets.shared.model.distributionfiltertree.shape.Shape;
import dk.mirasola.systemtraining.bridgewidgets.shared.model.distributionfiltertree.shape.ShapeElement;

import java.util.Arrays;

public class ShapeFactory {
    public static String shapeToString(Shape shape) {
        StringBuilder builder = new StringBuilder();
        shapeToString(shape, builder);
        return builder.toString();
    }

    public static void shapeToString(Shape shape, StringBuilder sb) {
        for (ShapeElement shapeElement : shape.getShapeElements()) {
            sb.append(ShapeElementFactory.shapeElementToString(shapeElement));
            sb.append("-");
        }
        sb.deleteCharAt(sb.length() - 1);
    }

    public static Shape stringToShape(String str) {
        int idx1 = str.indexOf("-");
        int idx2 = str.indexOf("-", idx1 + 1);
        int idx3 = str.indexOf("-", idx2 + 1);

        if (idx1 > 0 && idx2 > idx1 && idx3 > idx2) {
            ShapeElement se1 = ShapeElementFactory.stringToShapeElement(str.substring(0, idx1), false);
            ShapeElement se2 = ShapeElementFactory.stringToShapeElement(str.substring(idx1 + 1, idx2), false);
            ShapeElement se3 = ShapeElementFactory.stringToShapeElement(str.substring(idx2 + 1, idx3), false);
            ShapeElement se4 = ShapeElementFactory.stringToShapeElement(str.substring(idx3 + 1), false);
            return Shape.create(Arrays.asList(se1, se2, se3, se4), false);
        } else {
            throw new RuntimeException("Cannot parse: '" + str + "' to a shape");
        }
    }

    private ShapeFactory() {
    }


}
